import React, { Component } from 'react'
import { StatusBar, DatePickerAndroid, TimePickerAndroid, Picker, Modal, FlatList, TouchableOpacity, Alert, Image, View, BackHandler, ScrollView, Text, KeyboardAvoidingView } from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome'
import { Empty, Loading, TextInput, Button } from '../Components'
import { connect } from 'react-redux'

import CommodityDetailActions from '../Redux/CommodityDetailRedux'
import CouponActions from '../Redux/CouponRedux'
import CallActions from '../Redux/CallRedux'

let today = new Date()

// Styles
import styles from './Styles/CallScreenStyle'

class CallScreen extends Component {
  static navigationOptions = {
    title: '实时发单'
  }
  constructor(props) {
    super(props)
    const { state } = this.props.navigation
    this.state = {
      couponId: null,
      couponPrice: 0,
      commodityId: state.params.id,
      address: null,
      price: null,
      commodityLoading: true,
      couponLoading: true,
      loading: true,
      failure: false,
      couponModalVisible: false,
      type: 1, // 1 for realtime, 2 for order
      date: null,
      time: null
    }
  }
  componentDidMount() {
    this.props.getCommodity(this.state.commodityId, this.props.city.adcode)
    this.props.getCoupon(this.props.token)
    BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
  }
  componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
  }
  componentDidUpdate(prevProps, prevState) {
    /** commodity fetching **/
    if(prevProps.commodity.fetching
      && !this.props.commodity.fetching) {
      let commodity = this.props.commodity.payload
      if (commodity) {
        this.setState({commodityLoading: false,price: commodity.price})
      } else {
        this.setState({commodityLoading:false,failure:true})
      }
    }

    /** coupon list fetching **/
    if(prevProps.coupon.fetching
      && !this.props.coupon.fetching) {
      if (this.props.coupon.error) {
        this.setState({couponLoading:false, failure:true})
      } else {
        this.setState({couponLoading:false})
      }
    }

    /** screen loading **/

    /** call fetching **/
    if(prevProps.call.fetching
      && !this.props.call.fetching) {
      if (this.props.call.error) {
        Alert.alert('下单失败')
      } else {
        //Alert.alert('下单成功')
        this.props.navigation.navigate('OrderDetailScreen',{
          id:this.props.call.payload.id})
      }
    }
  }

  /** android goback **/
  onBackPress = () => {
    this.props.navigation.goBack()
    return true
  }

  /** choose coupon action **/
  chooseCoupon(id, money) {
    this.setState({
      couponId:id,
      couponPrice:money,
      couponModalVisible:false,
      price: this.props.commodity.payload.price - money,
    })
  }

  /** open datetime picker **/
  async selectDate() {
    try {
      const {action, year, month, day} = await DatePickerAndroid.open({
        date: new Date()
      });
      if (action !== DatePickerAndroid.dismissedAction) {
        this.selectTime()
        this.setState({date:year+'-'+month+'-'+day})
        // Selected year, month (0-11), day
      }
    } catch ({code, message}) {
      console.warn('Cannot open date picker', message);
    }
  }

  async selectTime() {
    try {
      const {action, hour, minute} = await TimePickerAndroid.open({
        hour: today.getHours(),
        minure: today.getMinutes()
      })
      if (action !== TimePickerAndroid.dismissedAction) {
        this.setState({time:hour+':'+minute})
      }
    } catch ({code, message}) {
      console.warn(message)
    }
  }

  /** do call **/
  submit = () => {
    const city = this.props.city
    if (!city) {
      Alert.alert('获取位置失败')
      return
    } else if (!this.state.address) {
      Alert.alert('请输入详细地址')
      return
    } else if (this.state.type == 2) {
      // if is order
      if (!this.state.date || !this.state.time) {
        Alert.alert('请选择预约时间')
        return
      }
    }
    datetime = this.state.date+' '+this.state.time
    if (this.state.type == 1) {
      datetime = null
    }
    this.props.getCall({
      'commodityId': this.state.commodityId, 
      'address': city.address + this.state.address, 
      'longitude': city.longitude, 
      'latitude': city.latitude, 
      'couponId': this.state.couponId, 
      'datetime': datetime,
      'token': this.props.token})
  }

  /** commodity shortcut **/
  _render_commodity(commodity) {
    return (
      <View style={{backgroundColor:'white',marginHorizontal:10,padding:10,flexDirection:'row',alignItems:'center',marginBottom:10}}>
        <Image style={{width:64,height:64,marginRight:10}}
          source={{uri:commodity.img}} />
        <View>
          <Text style={{fontSize:16,color:'rgba(0,0,0,0.85)',marginBottom:5}}>{commodity.name}</Text>
          <Text>
            价格:<Text style={{color:'#F24D16'}}>{commodity.price}</Text>  时长:<Text style={{color:'#F24D16'}}>{commodity.clock}</Text>
          </Text>
        </View>
      </View>
    )
  }

  /** address **/
  _render_address() {
    return (
      <View style={{borderTopWidth:1,borderTopColor:'#dfe6e9',padding:10}}>
        <Text>
          <Icon name='map-marker' size={18} />  {this.props.city && <Text
          style={{color:'rgba(0,0,0,0.85)'}}>{this.props.city.address}</Text>}
        </Text>
        <View>
          <TextInput placeholder='楼号门牌号'
            onChangeText={(value)=>this.setState({address:value})} />
        </View>
      </View>
    )
  }

  /** render time choice **/
  _render_time() {
    return (
      <View style={{padding:10}}>
        <View style={{flex:1,alignItems:'center',justifyContent:'center',flexDirection:'row'}}>
          <TouchableOpacity 
            style={this.state.type == 1 ? styles.time_item_active : styles.time_item}
            onPress={()=>{this.setState({type:1})}}>
            <Text style={{color:'#2d3436'}}>实时</Text></TouchableOpacity>
          <TouchableOpacity 
            style={this.state.type == 2 ? styles.time_item_active : styles.time_item}
            onPress={()=>{this.setState({type:1})}}>
            <Text style={{color:'#2d3436'}}>预约</Text></TouchableOpacity>
        </View>
        {this.state.type == 2 &&
        <TouchableOpacity onPress={()=>this.selectDate()}>
          <Text style={{alignSelf:'center'}}>
            <Icon name='clock-o' style={{fontSize:16,marginRight:5}} />
            <Text>  {this.state.date && this.state.time ? this.state.date+' '+this.state.time: '请选择预约时间'}</Text>
          </Text>
        </TouchableOpacity>}
      </View>
    )
  }

  /** render coupon item **/
  _render_coupon() {
    return (
      <TouchableOpacity
        onPress={()=>this.setState({couponModalVisible:true})}
        style={{marginHorizontal:10,marginBottom:10,padding:10,backgroundColor:'white',flexDirection:'row',justifyContent:'space-between',alignItems:'center'}}>
        <Text style={{color:'#333'}}>优惠券</Text>
        <Text style={{color:'#333'}}>
          {this.state.couponId &&
            <Text>- {this.state.couponPrice}  </Text>
          }
          <Icon name='chevron-right' style={{color:'lightgrey'}} />
        </Text>
      </TouchableOpacity>
    )
  }

  /** bottom action **/
  _render_action() {
    return (
      <View style={{flexDirection:'row'}}>
        <View style={{flex:1,backgroundColor:'white',
            paddingRight:10,justifyContent:'center'}}>
          <Text
            style={{color:'#F24D16',textAlign:'right'}}>
            实付款:￥{this.state.price}</Text>
        </View>
        <TouchableOpacity
          activeOpacity={0.6}
          onPress={this.submit}
          style={{paddingHorizontal:25,paddingVertical:15,
              backgroundColor:'#F24D16'}}>
          <Text style={{color:'rgba(255,255,255,0.85)',fontSize:16}}>
            提交订单</Text>
        </TouchableOpacity>
      </View>
    )
  }

  render () {
    if (this.state.commodityLoading || this.state.couponLoading) {
      return <Loading />
    } else if (this.state.failure) {
      return <Empty title='出错了' />
    }
    const commodity = this.props.commodity.payload

    /** coupon choose view **/
    let couponChooseView = null
    if (this.props.coupon.payload == '') { // need updated
      couponChooseView = <Empty title='无可用优惠券' />
    } else {
      couponChooseView = (
        <FlatList style={{padding:10}}
          keyExtractor={(item,index) => index}
          data={this.props.coupon.payload}
          renderItem={({item}) =>
              <TouchableOpacity
                disabled={commodity.price < item.min_amount}
                style={commodity.price >= item.min_amount ? [styles.item] : [styles.item,{opacity:0.38}]}
                onPress={()=>this.chooseCoupon(item.id, item.money)}>
                <View style={styles.left}>
                  <Text style={styles.money}>￥{item.money}</Text>
                </View>
                <View style={styles.right}>
                  <View>
                    <Text style={styles.title}>{commodity.price < item.min_amount && '[不可用]  '}{item.cid}</Text>
                    <Text style={{color:'#F24D16'}}>满{item.min_amount}可用</Text>
                    <Text style={{color:'darkgrey'}}>{item.send_time}-{item.expire_time}</Text>
                  </View>
                  {this.state.couponId == item.id &&
                  <Icon name='check' size={24} color='#F24D16' />}
                </View>
              </TouchableOpacity>
          }
        />
      )
    }

    return (
      <View style={{flex:1}}>
        <StatusBar translucent={false} barStyle='dark-content' backgroundColor='white' />
        <ScrollView style={styles.container}>
          <KeyboardAvoidingView behavior='position'>
            {this._render_commodity(commodity)}
            <View style={{backgroundColor:'white',paddingHorizontal:10,paddingVertical:5,margin:10,marginTop:0}}>
              {this._render_time()}
              {this._render_address()}
            </View>
            {this._render_coupon()}

          </KeyboardAvoidingView>
        </ScrollView>
        {this._render_action()}


        <Modal style={{flex:1}}
          animationType='slide'
          onRequestClose={()=>null}
          visible={this.state.couponModalVisible}>
          <View style={styles.header}>
            <TouchableOpacity style={{paddingHorizontal:20}}
              onPress={()=>this.setState({couponModalVisible:false})}>
              <Icon name='remove' size={20} color='rgba(0,0,0,0.54)' />
            </TouchableOpacity>
            <Text style={{fontSize:17,color:'rgba(0,0,0,0.85)',fontWeight:'bold'}}>选择优惠券</Text>
          </View>
          <View style={{flex:1,backgroundColor:'#efefef'}}>
            {couponChooseView}
          </View>
        </Modal>

      </View>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    token: state.user.payload.token,
    commodity: state.commodityDetail,
    coupon: state.coupon,
    city: state.city.payload,
    call: state.call,
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    getCommodity: (id, adcode) => dispatch(CommodityDetailActions.commodityDetailRequest(id, adcode)),
    getCoupon: (token) => dispatch(CouponActions.couponRequest(token)),
    getCall: (data) => dispatch(CallActions.callRequest(data))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(CallScreen)
